<?php

use Illuminate\Support\Facades\Event;

class Admin_UserResource extends BaseResource
{
	/**
	 * 资源视图目录
	 * @var string
	 */
	protected $resourceView = 'admin.user';

	/**
	 * 资源模型名称，初始化后转为模型实例
	 * @var string|Illuminate\Database\Eloquent\Model
	 */
	protected $model = 'User';

	/**!
	 * 资源标识
	 * @var string
	 */
	protected $resource = 'user';

	/**
	 * 资源数据库表
	 * @var string
	 */
	protected $resourceTable = 'user';

	/**
	 * 资源名称（中文）
	 * @var string
	 */
	protected $resourceName = '客户';

	/**
	 * 自定义验证消息
	 * @var array
	 */
	protected $validatorMessages = [
		'phone.unique' => '该手机号已经注册！',
	];

	public function users($user_group_id)
	{
		$page = Input::get('page', 1);
		$keywords = Input::get('keywords');
		$user_group_list = Config::get('site.user_group_list');

		$user_model = $this->model;
		if ($user_group_id == 1) {
			$query = $user_model->where('user_group_id', '=', 1); // ->leftJoin('customer', 'customer.user_id', '=', 'user.id');
		} else {
			if ($user_group_id == 2) {
				$query = $user_model->leftJoin('lawyer', 'lawyer.user_id', '=', 'user.id');
			} else {
				if ($user_group_id == 3) {
					$query = $user_model->leftJoin('company', 'company.user_id', '=', 'user.id');
				}
			}
		}

		$query->orderBy('user.created_at', 'DESC');

		if (!empty($user_group_id)) {
			$query->where('user_group_id', '=', $user_group_id);
		}
		if (!empty($keywords)) {
			$query->where('account', 'like', '%' . $keywords . '%');
			$query->orWhere('phone', 'like', '%' . $keywords . '%');
			$query->orWhere('email', 'like', '%' . $keywords . '%');
			if ($user_group_id == 3) {
				$query->orWhere('name', 'like', '%' . $keywords . '%');
			} else {
				$query->orWhere('realname', 'like', '%' . $keywords . '%');
			}
		}
		$datas = $query->paginate(Config::get('app.page_row'));
		$this->layout->content = View::make($this->resourceView . '.index')->with(compact('datas', 'keywords', 'user_group_list', 'user_group_id'));
	}

	public function edit($id)
	{
		$user = User::find($id);
		$user->info = App::make($user->group->model)->find($id);
		$this->layout->content = View::make($this->resourceView . '.edit')->with(compact('user'));
	}

	public function recommend($id)
	{
		$lawyer = Lawyer::find($id);
		if (!$lawyer) {
			return Redirect::back()->withInput()->with('error', '<strong>律师推荐失败。此律师不存在。</strong>');
		}

		try {
			$lawyer->is_recommended = 1;
			$lawyer->save();
		} catch (Exception $ex) {
			Log::error($ex);

			return Redirect::route('admin.users.edit', $id)->with('error', '<strong>律师推荐失败。</strong>');
		}

		return Redirect::route('admin.users.edit', $id)->with('success', '<strong>律师推荐成功。</strong>');
	}

	public function verify($id)
	{
		$user = User::find($id);
		$user->status = User::STATUS_VERIFIED_LAWYER;
		$user->save();

		UserScoresHistory::verifyLawer($user);
		// 发送站内消息
		$subject = "【恭喜】律师身份认证已通过";
		$message = $user->realname() . "律师，恭喜您！您的律师身份认证已通过，特送上20积分，请注意查收！";
		StationLetter::sendSystemLetter($subject, $message, $user);
		Event::fire("verify_lawyer", [$user]);

		return Redirect::route('admin.users.edit', $id);
	}

	public function addLawyer()
	{
		$work_scope_list = UtilsHelper::workScopeKeyValue();
		$this->layout->content = View::make('admin.user.addlawyer')->with(compact('work_scope_list'));
	}

	public function editLawyer($id)
	{
		$work_scope_list = UtilsHelper::workScope();
		$user = User::find($id);
		// 在这里lawyer有可能为null
		$lawyer = Lawyer::find($id);
		$this->layout->content = View::make('admin.user.editlawyer')->with(compact('work_scope_list', 'lawyer', 'user'));
	}

	public function storeLawyer()
	{
		$data = Input::all();
		$rules = [
			'phone'    => 'required|unique:user',
			'password' => 'required|confirmed',
			'realname' => 'required',
		];
		$messages = $this->validatorMessages;
		$validator = Validator::make($data, $rules, $messages);
		if ($validator->fails()) {
			return Redirect::back()->withInput()->withErrors($validator);
		}

		$user = User::storeLawyer($data);
		if ($user) {
			if ($avatar = Input::file('avatar')) {
				$upload_folder = Config::get('app.upload_dir') . '/user_img/' . $user->id;
				$upload_result = UploadHelper::uploadImage('avatar', $upload_folder);
				if ($upload_result['error'] == 0) {
					$user->avatar = $upload_result['files'][0]['path'];
					$user->save();
				}
			}
			if ($license_file = Input::file('license_file')) {
				$upload_folder = Config::get('app.upload_dir') . '/user_img/' . $user->id;
				$upload_result = UploadHelper::uploadImage('license_file', $upload_folder);
				if ($upload_result['error'] == 0) {
					$lawyer = Lawyer::find($user->id);
					$lawyer->license_file = $upload_result['files'][0]['path'];
					$lawyer->save();
				}
			}

			// 赠送积分，发送系统站内消息
			UserScoresHistory::registration($user);
			StationLetter::sendWelcomeLetter($user);

			return Redirect::route('admin.users.index', 2)->with('success', '<strong>律师添加成功。</strong>');
		} else {
			return Redirect::back()->withInput()->with('error', '<strong>律师添加失败。</strong>');
		}
	}

	public function updateLawyer($id)
	{
		$data = Input::all();
		$rules = [];
		if (isset($data['realname'])) {
			$rules['realname'] = 'required';
		}
		$messages = $this->validatorMessages;
		$validator = Validator::make($data, $rules, $messages);
		if ($validator->fails()) {
			return Redirect::back()->withInput()->withErrors($validator);
		}
		$user = User::find($id);
		$lawyer = Lawyer::find($id);
		if ($lawyer) {
			$user = User::updateLawyer($id, $data);
		} else {
			$user = User::updateUser($id, $data);
		}
		if ($user) {
			if ($avatar = Input::file('avatar')) {
				$upload_folder = Config::get('app.upload_dir') . '/user_img/' . $user->id;
				$upload_result = UploadHelper::uploadImage('avatar', $upload_folder);
				if ($upload_result['error'] == 0) {
					// 删除原来的图片
					if ($user->avatar) {
						File::delete($user->avatar);
					}
					$user->avatar = $upload_result['files'][0]['path'];
					$user->save();
				}
			}
			if ($license_file = Input::file('license_file')) {
				$upload_folder = Config::get('app.upload_dir') . '/user_img/' . $user->id;
				$upload_result = UploadHelper::uploadImage('license_file', $upload_folder);
				if ($upload_result['error'] == 0) {
					// 删除原来的图片
					if ($lawyer->license_file) {
						File::delete($lawyer->license_file);
					}
					$lawyer = Lawyer::find($user->id);
					$lawyer->license_file = $upload_result['files'][0]['path'];
					$lawyer->save();

				}

			}


			return Redirect::route('admin.users.index', 2)->with('success', '<strong>律师编辑成功。</strong>');
		} else {
			return Redirect::back()->withInput()->with('error', '<strong>律师编辑失败。</strong>');
		}
	}

	public function delete($id)
	{
		if ($user = User::find($id)) {
			$model_user = App::make($user->group->model)->where('user_id', $user->id)->first();
			if ($model_user) {
				$model_user->delete();
			}
			$user->delete();

			return Redirect::back()->withInput()->with('success', '<strong>删除成功。</strong>');

		} else {
			return Redirect::back()->withInput()->with('error', '<strong>用户不存在。</strong>');
		}
	}
}
